<template>
  <div>
    <a-form layout="horizontal" @submit="handleSubmit" :autoFormCreate="(form) => this.form = form" class="form">
      <a-card class="card" title="基本信息" :bordered="false">
        <a-row class="form-row" :gutter="16">
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="SKU"
              fieldDecoratorId="sku"
              :fieldDecoratorOptions="{
                rules: [{ required: true, message: '请输入SKU', whitespace: true}],
                initialValue: goods.sku
              }"
            >
              <a-input placeholder="请输入SKU" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="品牌"
              fieldDecoratorId="brand_id"
              :fieldDecoratorOptions="{
                rules: [{ required: true, message: '请选择品牌'}],
                initialValue: goods.brand_id
              }"
            >
              <a-select placeholder="请选择品牌">
                <a-select-option v-for="d in brands" :key="d.id">{{ d.name }}</a-select-option>
                <!-- <a-select-option v-for="item in brands" :key="item.id" :label="item.name" :value="item.id"></a-select-option> -->
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="名称"
              fieldDecoratorId="name"
              :fieldDecoratorOptions="{
                rules: [{ required: true, message: '请输入商品名称'}],
                initialValue: goods.name
              }"
            >
              <a-input placeholder="请输入商品名称" />
            </a-form-item>
          </a-col>

          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="类别"
              fieldDecoratorId="category_id"
              :fieldDecoratorOptions="{
                rules: [{ required: true, message: '请选择类别'}],
                initialValue: goods.category_id
              }"
            >
              <a-select placeholder="请选择类别">
                <a-select-option v-for="d in categories" :key="d.id">{{ d.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="娃娃个数"
              fieldDecoratorId="exchange_price"
              :fieldDecoratorOptions="{
                rules: [{ required: true, message: '请输入娃娃个数'}],
                initialValue: goods.exchange_price
              }"
            >
              <a-input placeholder="请输入娃娃个数" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="状态"
              fieldDecoratorId="is_listing"
              :fieldDecoratorOptions="{
                rules: [{ required: true, message: '请设置上架状态'}],
                initialValue: goods.is_listing
              }"
            >
              <a-radio-group name="radioGroup">
                <a-radio :value="true">上架</a-radio>
                <a-radio :value="false">下架</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="允许线上兑换"
              fieldDecoratorId="is_online"
              :fieldDecoratorOptions="{
                rules: [{ required: true, message: '请设置是否允许线上兑换'}],
                initialValue: goods.is_online
              }"
            >
              <a-radio-group name="radioGroup">
                <a-radio :value="true">允许</a-radio>
                <a-radio :value="false">不允许</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="是否推荐"
              fieldDecoratorId="recommended"
              :fieldDecoratorOptions="{
                rules: [{ required: true, message: '请设置是否推荐'}],
                initialValue: goods.recommended
              }"
            >
              <a-radio-group name="radioGroup">
                <a-radio :value="true">推荐</a-radio>
                <a-radio :value="false">不推荐</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="权重"
              fieldDecoratorId="weights"
              :fieldDecoratorOptions="{
                initialValue: goods.weights
              }"
            >
              <a-input placeholder="请输入权重" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
      <a-card class="card" title="图片信息" :bordered="false">
        <a-row>
          <a-col :md="24">
            <a-form-item
              label="商品列表封面"
              fieldDecoratorId="pic_url"
              :fieldDecoratorOptions="{
                rules: [{ required: true, message: '请上传商品列表封面'}],
                initialValue: goods.pic_url
              }"
            >
              <a-upload
                name="file"
                listType="picture-card"
                class="avatar-uploader"
                :showUploadList="false"
                action="//upload.qiniup.com"
                :beforeUpload="beforeCoverUpload"
                :data="imgForm"
                @change="handleCoverChange"
              >
                <img width=128 height=128 v-if="pic_url" :src="pic_url" />
                <div v-else>
                  <a-icon :type="loading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="24">
            <a-form-item
              label="详情页轮播图"
            >
              <a-upload
                action="//upload.qiniup.com"
                listType="picture-card"
                :fileList="fileList"
                :beforeUpload="beforeUpload"
                :data="imgForm"
                @change="handleChange"
              >
                <div v-if="fileList.length < 6">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
      <a-card class="card" title="详情描述" :bordered="false">
        <a-form-item
          fieldDecoratorId="detail"
          :fieldDecoratorOptions="{
            rules: [{ required: true, message: '请输入商品详情'}],
            initialValue: detail
          }"
        >
          <!-- <editor-tinymce v-model="detail" /> -->
          <tinymce v-model="detail"/>
        </a-form-item>
      </a-card>
      <a-card class="card" :bordered="false">
        <a-row>
          <a-col :span="4" :offset="10">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol">
              <a-button type='primary' htmlType='submit'>提交</a-button>
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
    </a-form>
  </div>
</template>
<script>
// import EditorTinymce from '@/components/EditorTinymce'
import Tinymce from '@/components/Tinymce'
import { getCategoryList } from '@/api/category'
import { getBrandList } from '@/api/brand'
import { getQiniuToken } from '@/api/qiniu'
import { getGoods, updateGoods } from '@/api/goods'
import { isNumber } from '@/utils/util'
import router from '@/router'

export default {
  name: 'EditGoods',
  components: {
    Tinymce
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
      loading: false,
      imgForm: {},
      bucketHost: '',
      fileList: [],
      listObj: [],
      form: null,
      pic_url: '',
      detail: '',
      goods: {},
      images: [],
      categories: [], // 分类列表
      brands: [], // 品牌列表
    }
  },
  created () {
    this.getGoods()
    this.getCategoryList()
    this.getBrandList()
  },
  methods: {
    getGoods() {
      getGoods(this.$route.params.id).then(res => {
        if (res.code === 0) {
          this.goods = res.data
          this.pic_url = this.goods.pic_url
          this.fileList = this.goods.images.map(image => {
            return {
              uid: image.id,
              name: '',
              url: image.url,
              status: 'done'
            }
          })
          this.detail = this.goods.detail
        }
      })
    },
    getCategoryList () {
      getCategoryList().then(res => {
        this.categories = res.data.data
      })
    },
    getBrandList () {
      getBrandList().then(res => {
        this.brands = res.data.data
      })
    },
    handleSubmit (e) {
      e.preventDefault()
      const _this = this
      this.form.validateFields((err, values) => {
        if (!err) {
          values.images = this.images.concat(_this.fileList.map(item => {
            let id = 0
            let url = ''
            if(isNumber(item.uid)) {
              id = item.uid
              url = item.url
            } else {
              url = _this.bucketHost + item.response.key
            }
            return {
              url,
              id
            }
          }))
          values.pic_url = _this.pic_url
          values.detail = _this.detail
          updateGoods(_this.goods.id, values).then(res => {
            if (res.code === 0) {
              _this.$message.success('修改成功')
              router.push({name: 'GoodsList'})
            }
          })
        }
      })
    },
    beforeCoverUpload: function () {
      let _this = this
      return getQiniuToken().then(res => {
        _this.bucketHost = res.data.bucketHost
        _this.imgForm = {
          // key: res.key,
          token: res.data.token
        }
      })
    },
    beforeUpload() {
      const me = this
      return getQiniuToken().then(res => {
        me.bucketHost = res.data.bucketHost
        me.imgForm = {
          // key: res.key,
          token: res.data.token
        }
      })
    },
    handleChange (info) {
      this.fileList = info.fileList
      if (info.file.status === 'uploading') {
        this.loading = true
      } else if (info.file.status === 'done') {
        this.loading = false
      } else if (info.file.status === 'error') {
        this.loading = false
        this.$message.error('上传图片失败，请重试')
      } else if (info.file.status === 'removed') {
        if (isNumber(info.file.uid)) {
          this.images.push({
            deleted: 1,
            id: info.file.uid
          })
        }
      }
    },
    handleCoverChange (info) {
      if (info.file.status === 'uploading') {
        this.loading = true
      } else if (info.file.status === 'done') {
        let key = info.file.response.key
        this.pic_url = `${this.bucketHost}${key}`
        this.loading = false
      } else if (info.file.status === 'error') {
        this.loading = false
        this.$message.error('上传图片失败，请重试')
      } else if (info.file.status === 'removed') {
        console.log('removed')
      }
    }
  }
}
</script>
